<?php
namespace app\adminbackstage\middleware;


use think\facade\Cache;
use think\facade\Log;
use think\facade\Request;


class AdminbackstageLog
{
    //进行请求操作日志的记录
    public function handle($request, \Closure $next)
    {
        Log::record('--------------------------------------------------------------------------------------');
        Log::record('请求url:'.Request::url(true).' 请求体:'.json_encode(Request::param(),JSON_UNESCAPED_UNICODE).' 请求头:'.json_encode(Request::header(),JSON_UNESCAPED_UNICODE));
        $token = app('request')->header('auth-token');
        $uid = Request::param("a_uid");
        if(!empty($uid)&&strpos(Request::url(true),"login")==false){
            //验证是否存在token
            if (!empty($token)) {
                if (Cache::get("admin-token".$uid)!=$token){
                    return json(['code' => -200, 'msg' => lang('您已在其他设备或浏览器登录!'), 'data' => '', 'count' => '']);
                }
            }else{
                 return json(['code' => -200, 'msg' => lang('请先登录!!'), 'data' => '', 'count' => '']);
            }
        }elseif(empty($uid)&&strpos(Request::url(true),"login")==false){
            return json(['code' => -200, 'msg' => lang('请先登录!!'), 'data' => '', 'count' => '']);
        }
        return $next($request);
    }

    //中间件支持定义请求结束前的回调机制，你只需要在中间件类中添加end方法。
    public function end(\think\Response $response)
    {
        // 回调日志记录
        Log::record($response->getContent());
    }
}